package com.sky.controller.user;

import com.sky.result.Result;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

@RestController
@Slf4j
@RequestMapping
@Api(tags = "搜索历史记录")
public class searchController {

    @Autowired
    private RedisTemplate redisTemplate;

    @GetMapping("/getSearchHistory")
    @ApiOperation("获取历史记录")
    public Result getSearch(String id) {

        //获取缓存的记录
        List o = (List<String>) redisTemplate.opsForValue().get(id);

        //集合反转
        Collections.reverse(o);

        return Result.success(o);
    }

    @GetMapping("/setSearchHistory")
    public Result setSearch(@RequestParam("id") String id, @RequestParam("search") String search) {

        log.info("收索关键词：{}", search);

        //从redis中获取用户已经搜索过的记录
        List<String> searchs = (List<String>) redisTemplate.opsForValue().get(id);

        //如果没有历史，就new一个历史
        if (searchs == null) {
            searchs = new ArrayList<>();
        }

        //限制历史容量长度为5，超过5条就删除第一条
        if (searchs.size() == 5) {
            searchs.remove(0);
        }

        //添加最新搜索到集合中
        searchs.add(search);

        //添加到redis
        redisTemplate.opsForValue().set(id, searchs);

        return Result.success();
    }
}
